package com.lzb.musicplayer.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lzb.basic.utils.TimeUtil;
import com.lzb.musicplayer.BasePlayerActivity;
import com.lzb.musicplayer.HomeActivity;
import com.lzb.musicplayer.R;
import com.lzb.musicplayer.adapter.InfoMusicAdapter;
import com.lzb.musicplayer.bean.GroupMusicInfo;
import com.lzb.musicplayer.bean.MusicFile;
import com.lzb.musicplayer.databinding.ActivityAlbumInfoBinding;
import com.lzb.musicplayer.dialog.DeleteDialog;
import com.lzb.musicplayer.dialog.InfoEditDialog;
import com.lzb.musicplayer.dialog.MusicEditDialog;
import com.lzb.musicplayer.dialog.PlaylistDialog;
import com.lzb.musicplayer.utils.MusicScanner;
import com.lzb.musicplayer.utils.MusicScannerUtil;
import com.lzb.musicplayer.utils.SaveListUtils;

import java.io.File;
import java.util.List;

public class AlbumInfoActivity extends BasePlayerActivity<ActivityAlbumInfoBinding> implements OnItemChildClickListener {

    private InfoMusicAdapter infoMusicAdapter;
    private List<MusicFile> list;
    private List<GroupMusicInfo> groupedList;
    private MusicFile musicFile;


    @Override
    protected int onCreate() {
        return R.layout.activity_album_info;
    }

    @Override
    protected void initView() {
        mDataBinding.ivAlbumInfoBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivEdit.setOnClickListener(this);
        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.ivRandomPlay.setOnClickListener(this);

        mDataBinding.rvMusicList.setLayoutManager(new LinearLayoutManager(mContext));
        infoMusicAdapter = new InfoMusicAdapter();
        mDataBinding.rvMusicList.setAdapter(infoMusicAdapter);
        infoMusicAdapter.addChildClickViewIds(R.id.ivInfoMusicItemEdit);
        infoMusicAdapter.setOnItemChildClickListener(this);

        Intent intent = getIntent();
        list = (List<MusicFile>) intent.getSerializableExtra("list");

        if (list != null && !list.isEmpty()) {
            groupedList = MusicScanner.groupByProperty(this, list);

            infoMusicAdapter.setList(groupedList);

            mDataBinding.audioPlayerView.setPlayList(list, 0);
            MusicFile musicFile = list.get(0);
            setFile(musicFile);
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivEdit) {//编辑
            showEditDialog(view, list);
        } else if (id == R.id.ivPlay) {//播放
            mDataBinding.audioPlayerView.startPlay();
        } else if (id == R.id.ivRandomPlay) {//随机播放
            mDataBinding.audioPlayerView.setSj();
            mDataBinding.audioPlayerView.startPlay();
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        int id = view.getId();
        if (id == R.id.ivInfoMusicItemEdit) {
            showEditDialog(view, infoMusicAdapter.getItem(position).getList());
        }
    }

    @Override
    protected void initData() {

    }

    private void setFile(MusicFile musicFile) {
        this.musicFile = musicFile;

        if (!TextUtils.isEmpty(musicFile.getAlbum())) {
            mDataBinding.tvMusicName.setText(musicFile.getAlbum());
        }
        if (!TextUtils.isEmpty(musicFile.getArtist())) {
            mDataBinding.tvArtistName.setText(musicFile.getArtist());
        }
        mDataBinding.tvDuration.setText(TimeUtil.getMmss(musicFile.getDuration()));

        Bitmap albumCover = MusicScannerUtil.getAlbumArt(this, musicFile.getAlbumCover());
        Bitmap bit = MusicScannerUtil.getAlbumArt((Activity) this, musicFile.getArtistCover());

        if (musicFile.getGroupKey().equals("0")) {
            if (albumCover != null) {
                mDataBinding.ivImg.setImageBitmap(albumCover);
            } else {
                mDataBinding.ivImg.setImageResource(R.drawable.zhuanji_pic);
            }
        }

        if (musicFile.getGroupKey().equals("1")) {
            if (bit != null) {
                mDataBinding.ivImg.setImageBitmap(bit);
            } else {
                mDataBinding.ivImg.setImageResource(R.drawable.yishujia_pic);
            }
        }
        if (bit != null) {
            mDataBinding.ivArtistImg.setImageBitmap(bit);
        } else {
            mDataBinding.ivArtistImg.setImageResource(R.drawable.yishujia);
        }
    }

    @Override
    public void onPlaybackStateChanged(boolean isPlaying) {
        if (isPlaying) {
            mDataBinding.audioPlayerView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPlaybackStateChanged(int state) {

    }

    @Override
    public void onProgressUpdated(long position, long duration) {

    }

    @Override
    public void onTrackChanged(MusicFile currentTrack) {

    }

    private void showEditDialog(View view, List<MusicFile> musicFile) {
        InfoEditDialog dialog = new InfoEditDialog(mContext);
        BasePopupView basePopupView = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .offsetX(0)//x轴偏移
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(view).hasShadowBg(false) // 去掉半透明背景
                .asCustom(dialog);
        dialog.setListener(new InfoEditDialog.Ilistener() {
            @Override
            public void clickItem(int pos) {
                switch (pos) {
                    case 0://播放
                        setFragmentMusicList(musicFile);
                        break;
                    case 1://加入播放队列
                        SaveListUtils.saveDlList(AlbumInfoActivity.this, musicFile);
                        break;
                    case 2://加入播放列表
                        showPlaylistDialog(musicFile);
                        break;
                    case 3://删除
                        if (view.getId() == R.id.ivEdit) {
                            if (list.get(0).getGroupKey().equals("0")) {
                                showDeleteDialog(0, list);
                            } else {
                                showDeleteDialog(1, list);
                            }
                        }
                        break;
                }
            }
        });
        basePopupView.show();
    }

    private void setFragmentMusicList(List<MusicFile> listFile) {
        if (listFile != null && !listFile.isEmpty()) {
            mDataBinding.audioPlayerView.setPlayList(listFile, 0);
            mDataBinding.audioPlayerView.startPlay();
        }
    }

    private void showDeleteDialog(int type, List<MusicFile> musicFile) {
        DeleteDialog dialog = new DeleteDialog(mContext);
        if (type == 0) {
            dialog.setText(getString(R.string.album_delete_tip));
        } else if (type == 1) {
            dialog.setText(getString(R.string.artist_delete_tip));
        } else {
            dialog.setText(getString(R.string.music_delete_tip));
        }
        dialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                if (type == 2) {
                    setDelete(musicFile);
                } else {
                    for (MusicFile file : list) {
                        FileUtils.delete(file.getPath());
                    }
                    ToastUtils.showShort(getString(R.string.delete_suc));
                    finish();
                }
            }
        });
        dialog.show();
    }

    private void setDelete(List<MusicFile> list1) {
        if (list1 != null && !list1.isEmpty()) {
            FileUtils.delete(list1.get(0).getPath());
            list.removeAll(list1);
            if (mDataBinding.audioPlayerView.getList() != null && mDataBinding.audioPlayerView.getList().equals(list)) {
                mDataBinding.audioPlayerView.setVisibility(View.GONE);
                mDataBinding.audioPlayerView.pause();
            }
            setListData();
        }
    }

    private void setListData() {
        groupedList = MusicScanner.groupByProperty(this, list);
        infoMusicAdapter.setList(groupedList);
    }

    private void showPlaylistDialog(List<MusicFile> musicFile) {
        PlaylistDialog playlistDialog = new PlaylistDialog(mContext);
        playlistDialog.setMusicFileList(musicFile);
        playlistDialog.show();
    }

}